package com.mo.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.mo.constant.Constants;
import com.mo.model.TCustomer;
import com.mo.query.CustomerQuery;
import com.mo.result.CustomerExcel;
import com.mo.result.R;
import com.mo.service.CustomerService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author mo
 * version
 */
@RestController
public class CustomerController {

    @Resource
    private CustomerService customerService;

    @PostMapping("/api/convertCustomer")
    public R convertCustomer(@RequestBody CustomerQuery customerQuery) {
        Boolean save = customerService.saveCustomer(customerQuery);
        return save ? R.OK() : R.FAIL();
    }

    @GetMapping("api/customers")
    public R getCustomer(@RequestParam(value = "current", required = false) Integer current) {
        if (current == null) {
            current = 1;
        }
        PageInfo<TCustomer> pageInfo = customerService.getCustomersByPage(current);
        return R.OK(pageInfo);
    }
    @GetMapping("api/customer/{id}")
    public R getCustomerById(@PathVariable("id") Integer id) {
        TCustomer customer = customerService.getCustomersById(id);
        return R.OK(customer);
    }

    @GetMapping(value = "/api/exportExcel")
    public void exportExcel(HttpServletResponse response, @RequestParam(value = "ids", required = false) String ids) throws IOException {
        //想让浏览器弹出下载框，后端要设置一下响应头，来告诉前端来下载这个文件，而不是解析渲染这个文件
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");                                      //有中文防止乱码
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(Constants.EXCEL_FILE_NAME + System.currentTimeMillis(), StandardCharsets.UTF_8) + ".xlsx");

        //2、后端查询数据库的数据，把数据写入Excel，然后把Excel以IO流的方式输出到前端浏览器（我们来实现）

        //没有数据就给个空list
        List<String> idList = StringUtils.hasText(ids) ? Arrays.asList(ids.split(",")) : new ArrayList<>();
        List<CustomerExcel> dataList = customerService.getCustomerByExcel(idList);

        EasyExcel.write(response.getOutputStream(), CustomerExcel.class)
                .sheet()
                .doWrite(dataList);
    }
}

